package org.brownflat.watergate.domain;

import org.brownflat.watergate.scm.Revision;
import org.brownflat.watergate.scm.RevisionChange;
import org.brownflat.watergate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * <p>&copy Rupert Jones 2012</p>
 *
 * @author rup
 */
@Component
public class CommitBuilder {

    @Autowired
    private CommitElementBuilder commitElementBuilder;

    @Autowired
    private UserService userService;

    public Commit build(Branch branch, User user) {
        Commit commit = new Commit();
        commit.setBranch(branch);
        commit.setUser(user);
        return commit;
    }

    public Commit build(Branch branch, Revision revision) {
        Commit commit = new Commit();
        commit.setBranch(branch);
        commit.setMessage(revision.getMessage());
        commit.setRevision(revision.getRevision());
        commit.setCreatedAt(revision.getDate());
        commit.setUser(userService.findUserForRevision(branch.getRepository(), revision));
        for(RevisionChange change : revision.getRevisionChanges()) {
            commit.addCommitElement(commitElementBuilder.build(commit, change));
        }
        User user = userService.findUserForRevision(branch.getRepository(), revision);
        commit.setUser(user);
        return commit;
    }
}
